package IC.Parser;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class ParserTester { 

	public static void main(String[] args) {
		if (args.length != 1){
			System.err.println("Wrong number of arguments. Only path to the IC files directory");
			return;
		}

		File dir = new File(args[0]);
		if (!dir.isDirectory()){
			System.out.println(args[0] + "is not a directory or not found");
		}

		File[] files = dir.listFiles();
		try {
			for (File file : files){
				if (file.isFile()){
					IC.Compiler.main(new String[]{file.getPath(), "-print-ast", "-debug"});
					
					if (getOurOutputFile(file).exists() && (compareOutputs(file))) {
						System.out.println("Compared " + file.getName() + " output successflly\n");
					} else {
						System.out.println("Comparison of " + file.getName() + " failed\n");
					}
				}
			} 
		}catch (Exception e){
			System.out.println("Error: " + e.getMessage());
		}

	}

	private static boolean compareOutputs(File file) throws IOException{
		BufferedReader expOutputBuf = new BufferedReader(new FileReader(getExpectedOutputFile(file)));
		BufferedReader ourOutputBuf = new BufferedReader(new FileReader(getOurOutputFile(file)));

		String currentExpectedLine;
		String currLine;
		currentExpectedLine = expOutputBuf.readLine();
		currLine = ourOutputBuf.readLine();

		boolean result;

		while (currentExpectedLine != null && currLine != null){
			if (!(currLine.startsWith("Parsed") && currentExpectedLine.startsWith("Parsed")) && 
					!currLine.toString().equals(currentExpectedLine) && 
					!(currLine.startsWith("Abstract") && currentExpectedLine.startsWith("Abstract"))){  
				System.err.println("Test failed: expected : [" + currentExpectedLine  + "], current : [" + currLine + "]");
				result = false;
				break;
			}	
			currentExpectedLine = expOutputBuf.readLine();
			currLine = ourOutputBuf.readLine();
		} 
		if (currentExpectedLine == null && currLine == null){
			result =  true;
		}
		else {
			result =  false;
		}

		if (expOutputBuf != null)
			expOutputBuf.close();
		if (ourOutputBuf != null)
			ourOutputBuf.close();

		return result;
	}

	private static File getExpectedOutputFile(File file) throws IOException{
		return getOutputFile(file, "exp");
	}

	private static File getOurOutputFile(File file) throws IOException{
		return getOutputFile(file, "our");
	}

	private static File getOutputFile(File file, String dir) throws IOException{
		String fileName = getFileName(file);
		return new File(file.getParent() + File.separatorChar + dir + File.separatorChar + fileName + ".ast.txt");
	}

	private static String getFileName(File file){
		String nameWithExt = file.getName();
		int index = nameWithExt.lastIndexOf(".");
		return nameWithExt.substring(0, index);
	}


}
